//
//  CZUserAccount.swift
//  WeiBo
//
//  Created by Apple on 16/9/5.
//  Copyright © 2016年 KY. All rights reserved.
//

import UIKit
//  用户账号模型
class CZUserAccount: NSObject, NSCoding {
    //  用户授权的唯一票据
    var access_token: String?
    //  access_token的生命周期，单位是秒数
    var expires_in: TimeInterval = 0 {
        didSet {
            //  过期时间 = 获取accesstoken的时间 + 过期秒数
            expiresDate = Date().addingTimeInterval(expires_in)
        }
    }
    //  过期时间
    var expiresDate: Date?
    //  授权用户的UID
    var uid: Int64 = 0
    //  用户名
    var name: String?
    //  用户头像
    var avatar_large: String?
    
    //  kvc构造函数
    init(dic: [String: Any]) {
        super.init()
        setValuesForKeys(dic)
    }
    
    //  防止崩溃
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        
    }
    
    // MARK:    --归档解档方法
    //  归档
    func encode(with aCoder: NSCoder) {
        aCoder.encode(access_token, forKey: "access_token")
        aCoder.encode(uid, forKey: "uid")
        aCoder.encode(expiresDate, forKey: "expiresDate")
        aCoder.encode(name, forKey: "name")
        aCoder.encode(avatar_large, forKey: "avatar_large")
    }
    //  解档
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObject(forKey: "access_token") as? String
        uid = aDecoder.decodeInt64(forKey: "uid")
        expiresDate = aDecoder.decodeObject(forKey: "expiresDate") as? Date
        name = aDecoder.decodeObject(forKey: "name") as? String
        avatar_large = aDecoder.decodeObject(forKey: "avatar_large") as? String
        
    }
    
    //  重写描述信息属性
    override var description: String {
        let keys = ["access_token", "uid", "expiresDate", "name", "avatar_large"]
        return dictionaryWithValues(forKeys: keys).description
    }
    
    //  保存用户对象
    func saveUserAccount() -> Bool {
        let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("userAccount.archive")
        
        print(path)
        
        let result = NSKeyedArchiver.archiveRootObject(self, toFile: path)
        return result
    
    }
    
    
    //  读取用户对象
    class func loadUserInfo() -> CZUserAccount? {
        let path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("userAccount.archive")
        let userAccount = NSKeyedUnarchiver.unarchiveObject(withFile: path) as? CZUserAccount
        return userAccount
    }
    
}
